//
//  PullView.m
//  瀑布流封装
//
//  Created by 常宽 on 14/11/1.
//  Copyright (c) 2014年 常宽. All rights reserved.
//

#import "PullView.h"
#import "PullLayout.h"
#import "PullCollectionViewCell.h"
#import "MJRefresh.h"
#import "CKCar.h"

@interface PullView ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, PullLayoutDelegate>


// 临时监听,目的开始时不让获取数据走两次
@property (nonatomic, assign)NSInteger countI;

@end

@implementation PullView

- (void)dealloc
{
    [_string release];
    [_bigArray release];
    [_collectionView release];
    [super dealloc];
}


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.bigArray = [NSMutableArray array];
        self.string = [NSString string];
        self.countx = 1;
        self.countI = 0;
        PullLayout *flow = [[PullLayout alloc] init];
        flow.delegate = self;
        flow.sectionInset = UIEdgeInsetsMake(0, 0, 10, 0);
        flow.minimumInteritemSpacing = 5;
        flow.minimumLineSpacing = 5;
//        NSLog(@"%f", flow.itemSize.height);
        
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:flow];
        [self addSubview:_collectionView];
        [_collectionView release];
        [flow release];
    }
    return self;
}
- (void)netWrok
{
    // 临时监听,目的开始时不让获取数据走两次
    if (_countI != 0) {
//        NSLog(@"请求前:%@", self.string);
        
        [Connection networkHandlerWith:self.string block:^(id result) {
            
            for (NSDictionary *dic in [result objectForKey:@"data"]) {
                CKCar *car = [[CKCar alloc] init];
                [car setValuesForKeysWithDictionary:dic];
                [self.bigArray addObject:car];
                [car release];
            }
            
            [_collectionView reloadData];

            // 2.2秒后刷新表格UI
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 刷新表格
                [self.collectionView reloadData];
                
                // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
                [self.collectionView footerEndRefreshing];
                
                self.string = [self.string stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"pageNo=%d&", self.countx] withString:[NSString stringWithFormat:@"pageNo=%d&", self.countx + 1]];
//                NSLog(@"_countx增加前:%@", self.string);
                
                _countx ++;
//                NSLog(@"self.countx %d", self.countx);
            });
        }];
    }
    _countI++;
}



- (void)layoutSubviews
{
    [super layoutSubviews];
    [self netWrok];

    [self setupRefresh];
    [self viewCreate];
    
    [[SDImageCache sharedImageCache] clearDisk];
    
    [[SDImageCache sharedImageCache] clearMemory];
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(noScreenRefresh:)];
    swipe.direction = UISwipeGestureRecognizerDirectionDown;
    [self addGestureRecognizer:swipe];
    [swipe release];
    
}
// 轻扫手势，无网刷新，（变相下拉刷新)
- (void)noScreenRefresh:(UISwipeGestureRecognizer *)sender
{
    [self layoutSubviews];
}

// 视图创建
- (void)viewCreate
{
    
    self.collectionView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    
    //注册
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    [_collectionView registerClass:[PullCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
}

#pragma mark 协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.bigArray.count;
}

//item的重用池
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PullCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.car = [self.bigArray objectAtIndex:indexPath.item];
    
    //重新设置imageView的高度
    CGSize size = cell.imageView.image.size;
    float scale = size.width / (_collectionView.frame.size.width / 2 - 5);
    if (scale != 0) {
        float height = size.height / scale;
        [cell.imageView setFrame:CGRectMake(0, 0, (_collectionView.frame.size.width / 2 - 5), height)];
    }
    
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // UIImageView自适应
    UIImageView *img = [[[UIImageView alloc]init]autorelease];
    CKCar *car = [self.bigArray objectAtIndex:indexPath.item];
    
    [img sd_setImageWithURL:[NSURL URLWithString:car.image]];
    
    UIImage *aImage = img.image;
    if (aImage == nil) {
        aImage = [UIImage imageNamed:@"NoPicture.jpg"];
    }
    
    CGSize size = aImage.size;
    CGFloat w = (_collectionView.frame.size.width / 2) - 5;
    
    
//#warning 等会可能会回来做判断
    float height = 50.f;
    float scale = size.width / w;
    if (scale > 0) {
        height = size.height /scale;
    }
    
    // 字符串自适应
    NSString *str = car.title;
    CGRect rect = [str boundingRectWithSize:CGSizeMake(self.collectionView.frame.size.width / 2 - 5, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.f]} context:nil];
    

    //自适应高度
    return CGSizeMake(w , height + rect.size.height + 10);
}


// 点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"selected:%ld",indexPath.item);
    // 获得ID
    CKCar *car = [self.bigArray objectAtIndex:indexPath.item];
//    NSString *string = car.idNumder;
//    NSLog(@"id: %@", string);
    self.block(car);

    
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.collectionView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.collectionView addFooterWithTarget:self action:@selector(netWrok)];
    [self.collectionView footerEndRefreshing];
    //
//    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    self.collectionView.headerPullToRefreshText = @"下拉以上弦...";
//    self.collectionView.headerReleaseToRefreshText = @"松开即可上弦...";
//    self.collectionView.headerRefreshingText = @"上弦中...";
//    
//    self.collectionView.footerPullToRefreshText = @"上拉可以加载更多数据了";
//    self.collectionView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
//    self.collectionView.footerRefreshingText = @"加载中";
    
//    self.countx = 1;
//    NSLog(@"se.countx %d", self.countx);
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.collectionView reloadData];
        //        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collectionView  headerEndRefreshing];
    });
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
